﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infrastructure;
using Microsoft.Practices.Prism.Commands;
using System.Windows;
using System.Threading;
using System.IO;
using DBDataAccessLib;
using System.Collections.ObjectModel;

namespace ManageImages.ViewModel
{
    public class ManageImagesViewModel : ViewModelBase
    {
        public DelegateCommand<object> AddStationNameCommand { get; set; }
        public DelegateCommand<object> DeleteStationNameCommand { get; set; }
        //public DelegateCommand<object> AddWCNOCommand { get; set; }
        //public DelegateCommand<object> DeleteWCNOCommand { get; set; }

        public ManageImagesViewModel()
        {
            SelectedStationNames = new List<string>();
            GetWCNOLines();
            AddStationNameCommand = new DelegateCommand<object>(OnAddStationNameCommand, OnCanAddStationNameCommand);
            DeleteStationNameCommand = new DelegateCommand<object>(OnDeleteStationNameCommand, OnCanDeleteStationNameCommand);
            //AddWCNOCommand = new DelegateCommand<object>(OnAddWCNOCommand, OnCanAddWCNOCommand);
            //DeleteWCNOCommand = new DelegateCommand<object>(OnDeleteWCNOCommand, OnCanDeleteWCNOCommand);
        }

        //public void OnAddWCNOCommand(object obj)
        //{
        //    string wcno = WCNOLines.FirstOrDefault(p => p.ToLower() == this.AddedWCNOName.ToLower().Trim());
        //    if (!string.IsNullOrWhiteSpace(wcno))
        //    {
        //        ModalWindowService.ShowMessage("该流水线名称已存在，添加失败。");
        //        return;
        //    }
        //    int val = StationNameDataAccess.AddNewWCNO(this.AddedWCNOName);
        //    if (val > 0)
        //    {
        //        WCNOLines.Add(AddedWCNOName);
        //        if (string.IsNullOrWhiteSpace(SelectedWCNOLine)) SelectedWCNOLine = AddedWCNOName;
        //        if (string.IsNullOrWhiteSpace(SelectedDeleteWCNOLine)) SelectedDeleteWCNOLine = AddedWCNOName;
        //        ModalWindowService.ShowMessage("添加成功。");
        //    }
        //    else ModalWindowService.ShowMessage("添加失败，请稍候再试。");
        //}
        //public bool OnCanAddWCNOCommand(object obj)
        //{
        //    return !string.IsNullOrWhiteSpace(AddedWCNOName);
        //}
        //public void OnDeleteWCNOCommand(object obj)
        //{
        //    ModalWindowService.ShowConfirmMessage("确定要删除选中的流水线吗？", result =>
        //    {
        //        if (MessageBoxResult.Yes == result)
        //        {
        //            bool isSuccess = true;
        //            this.IsBusy = true;
        //            MessageContent = "正在删除流水线...";
        //            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
        //            {
        //                SynchronizationContext context = currentContext as SynchronizationContext;
        //                string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        //                int val = StationNameDataAccess.DeleteWCNOLine(SelectedDeleteWCNOLine);
        //                if (val <= 0) isSuccess = false;
        //                else
        //                {
        //                    if (Directory.Exists(Helper.ServerUrl + SelectedDeleteWCNOLine))
        //                    {
        //                        Directory.CreateDirectory(Helper.ServerUrl + SelectedDeleteWCNOLine + timeStamp);
        //                        string[] subDirs = Directory.GetDirectories(Helper.ServerUrl + SelectedDeleteWCNOLine);
        //                        foreach (var subDir in subDirs)
        //                        {
        //                            DirectoryInfo dirInfo = new DirectoryInfo(subDir);
        //                            Directory.CreateDirectory(Helper.ServerUrl + SelectedDeleteWCNOLine + timeStamp + "\\" + dirInfo.Name);
        //                            foreach (var filePath in Directory.GetFiles(Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + dirInfo.Name))
        //                            {
        //                                FileInfo info = new FileInfo(filePath);
        //                                File.Copy(filePath, Helper.ServerUrl + SelectedDeleteWCNOLine + timeStamp + "\\" + dirInfo.Name + "\\" + info.Name, true);
        //                            }
        //                        }
        //                        Directory.Delete(Helper.ServerUrl + SelectedDeleteWCNOLine, true);
        //                    }
        //                }
        //                context.Send(new SendOrPostCallback(p =>
        //                {
        //                    IsBusy = false;
        //                    if (isSuccess) ModalWindowService.ShowMessage("删除成功。");
        //                    else ModalWindowService.ShowMessage("删除失败。");
        //                    GetWCNOLines();
        //                }), null);
        //            }), SynchronizationContext.Current);
        //        }
        //    });
        //}
        //public bool OnCanDeleteWCNOCommand(object obj)
        //{
        //    return !string.IsNullOrWhiteSpace(this.SelectedDeleteWCNOLine);
        //}

        private void GetWCNOLines()
        {
            this.IsBusy = true;
            MessageContent = "正在获取流水线信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> wcnos = LineNameDataAccess.GetLineCodesByJIBU("70").ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.WCNOLines = p as ObservableCollection<string>;
                    if (WCNOLines.Count > 0)
                    {
                        SelectedWCNOLine = this.WCNOLines.First();
                        SelectedDeleteWCNOLine = this.WCNOLines.First();
                    }
                    else
                    {
                        if (StationNames != null) StationNames.Clear();
                    }
                }), wcnos);
            }), SynchronizationContext.Current);
        }

        public void OnDeleteStationNameCommand(object obj)
        {
            if (SelectedStationNames.Count == 0)
            {
                ModalWindowService.ShowMessage("请先选择要删除的工位。");
                return;
            }
            ModalWindowService.ShowConfirmMessage("确定要删除选中的工位吗？", result =>
            {
                if (MessageBoxResult.Yes == result)
                {
                    this.IsBusy = true;
                    MessageContent = "正在删除工位...";
                    List<string> failedStationNames = new List<string>();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                    {
                        SynchronizationContext context = currentContext as SynchronizationContext;
                        string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                        foreach (var item in SelectedStationNames)
                        {
                            int val = StationNameDataAccess.DeleteStationName(item, SelectedDeleteWCNOLine);
                            if (val <= 0) failedStationNames.Add(item);
                            else
                            {
                                if (Directory.Exists(Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + item))
                                {
                                    Directory.CreateDirectory(Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + item + timeStamp);
                                    foreach (var filePath in Directory.GetFiles(Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + item))
                                    {
                                        FileInfo info = new FileInfo(filePath);
                                        File.Copy(filePath, Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + item + timeStamp + "\\" + info.Name, true);
                                    }
                                    Directory.Delete(Helper.ServerUrl + SelectedDeleteWCNOLine + "\\" + item, true);
                                }
                            }
                        }
                        context.Send(new SendOrPostCallback(p =>
                        {
                            IsBusy = false;
                            if (failedStationNames.Count == 0) ModalWindowService.ShowMessage("删除成功。");
                            else ModalWindowService.ShowMessage("删除失败，失败的工位为：" + string.Join(",", failedStationNames.ToArray()) + "。");
                            GetStationNames(SelectedDeleteWCNOLine);
                            SelectedStationNames = new List<string>();
                        }), null);
                    }), SynchronizationContext.Current);
                }
            });
        }

        public bool OnCanDeleteStationNameCommand(object obj)
        {
            return true;
        }


        public void OnAddStationNameCommand(object obj)
        {
            if (!string.IsNullOrWhiteSpace(StationNameDataAccess.GetAllStationNames(SelectedWCNOLine).FirstOrDefault(p => p == AddedStationName)))
            {
                ModalWindowService.ShowMessage("该工位名称已存在，添加失败。");
                return;
            }
            int val = StationNameDataAccess.AddNewStation(this.AddedStationName, this.SelectedWCNOLine);
            if (val > 0)
            {
                if (StationNames != null && SelectedWCNOLine == SelectedDeleteWCNOLine) StationNames.Add(AddedStationName);
                ModalWindowService.ShowMessage("添加成功。");
            }
            else ModalWindowService.ShowMessage("添加失败，请稍候再试。");
        }

        public bool OnCanAddStationNameCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(AddedStationName) && !string.IsNullOrWhiteSpace(SelectedWCNOLine);
        }

        private void GetStationNames(string wcnoLine)
        {
            this.IsBusy = true;
            MessageContent = "正在获取工位信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> stations = StationNameDataAccess.GetAllStationNames(wcnoLine).ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.StationNames = p as ObservableCollection<string>;
                }), stations);
            }), SynchronizationContext.Current);
        }

        private string addedWCNOName;

        public string AddedWCNOName
        {
            get { return addedWCNOName; }
            set
            {
                addedWCNOName = value.Trim();
                OnPropertyChanged("AddedWCNOName");
                //AddWCNOCommand.RaiseCanExecuteChanged();
            }
        }

        private string addedStationName;

        public string AddedStationName
        {
            get { return addedStationName; }
            set
            {
                addedStationName = value.Trim();
                OnPropertyChanged("AddedStationName");
                AddStationNameCommand.RaiseCanExecuteChanged();
            }
        }

        private List<string> selectedStationNames;

        public List<string> SelectedStationNames
        {
            get { return selectedStationNames; }
            set
            {
                selectedStationNames = value;
                OnPropertyChanged("SelectedStationNames");
            }
        }

        private ObservableCollection<string> stationNames;

        public ObservableCollection<string> StationNames
        {
            get { return stationNames; }
            set
            {
                stationNames = value;
                OnPropertyChanged("StationNames");
            }
        }


        private ObservableCollection<string> wcnoLines;

        public ObservableCollection<string> WCNOLines
        {
            get { return wcnoLines; }
            set
            {
                wcnoLines = value;
                OnPropertyChanged("WCNOLines");
            }
        }

        private string selectedWCNOLine;

        public string SelectedWCNOLine
        {
            get { return selectedWCNOLine; }
            set
            {
                if (selectedWCNOLine != value)
                {
                    selectedWCNOLine = value;
                    OnPropertyChanged("SelectedWCNOLine");
                    AddStationNameCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private string selectedDeleteWCNOLine;

        public string SelectedDeleteWCNOLine
        {
            get { return selectedDeleteWCNOLine; }
            set
            {
                if (selectedDeleteWCNOLine != value)
                {
                    selectedDeleteWCNOLine = value;
                    OnPropertyChanged("SelectedDeleteWCNOLine");
                    if (value != null) GetStationNames(value);
                    //DeleteWCNOCommand.RaiseCanExecuteChanged();
                    DeleteStationNameCommand.RaiseCanExecuteChanged();
                }
            }
        }
    }
}
